package com.example.app.utils;

import com.alibaba.fastjson.JSON;
import com.example.app.constants.CommonConstants;
import com.example.app.model.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by wangtao on 2018/3/13.
 */
@Configuration
public class RequestUtil {

    public static void setLoginUser(User user) throws Exception{
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if(requestAttributes == null){
            throw new NullPointerException();
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        HttpSession session = request.getSession();
        if(session != null){
            request.getSession().setAttribute(CommonConstants.LOGIN_USER, JSON.toJSON(user));
        }
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public static User getLoginUser() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String token = request.getHeader("access_token");
        User user = null;
        try {
            JwtHelper jwtHelper = SpringContextUtil.getBean(JwtHelper.class);
            user = jwtHelper.getUserByToken(token);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        if (user == null) {
            throw new RuntimeException("用户session失效");
        }
        return user;
    }
}
